﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace StockWarningListener
{
    public class ImageAI
    {

        public Bitmap bmpobj;
        public ImageAI(Bitmap pic)
        {
            bmpobj = new Bitmap(pic);    //转换为Format32bppRgb
        }

        /// <summary>
        /// 根据RGB，计算灰度值
        /// </summary>
        /// <param name="posClr">Color值</param>
        /// <returns>灰度值，整型</returns>
        private int GetGrayNumColor(System.Drawing.Color posClr)
        {
            return (posClr.R * 19595 + posClr.G * 38469 + posClr.B * 7472) >> 16;
        }

        /// <summary>
        /// 灰度转换,逐点方式
        /// </summary>
        public void GrayByPixels()
        {
            for (int i = 0; i < bmpobj.Height; i++)
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    int tmpValue = GetGrayNumColor(bmpobj.GetPixel(j, i));
                    bmpobj.SetPixel(j, i, Color.FromArgb(tmpValue, tmpValue, tmpValue));
                }
            }
        }

        /// <summary>
        /// 去图形边框
        /// </summary>
        /// <param name="borderWidth"></param>
        public void ClearPicBorder(int borderWidth)
        {
            for (int i = 0; i < bmpobj.Height; i++)
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    if (i < borderWidth || j < borderWidth || j > bmpobj.Width - 1 - borderWidth || i > bmpobj.Height - 1 - borderWidth)
                        bmpobj.SetPixel(j, i, Color.FromArgb(255, 255, 255));
                }
            }
        }

        /// <summary>
        /// 灰度转换,逐行方式
        /// </summary>
        public void GrayByLine()
        {
            Rectangle rec = new Rectangle(0, 0, bmpobj.Width, bmpobj.Height);
            BitmapData bmpData = bmpobj.LockBits(rec, ImageLockMode.ReadWrite, bmpobj.PixelFormat);// PixelFormat.Format32bppPArgb);
                                                                                                    //    bmpData.PixelFormat = PixelFormat.Format24bppRgb;
            IntPtr scan0 = bmpData.Scan0;
            int len = bmpobj.Width * bmpobj.Height;
            int[] pixels = new int[len];
            Marshal.Copy(scan0, pixels, 0, len);

            //对图片进行处理
            int GrayValue = 0;
            for (int i = 0; i < len; i++)
            {
                GrayValue = GetGrayNumColor(Color.FromArgb(pixels[i]));
                pixels[i] = (byte)(Color.FromArgb(GrayValue, GrayValue, GrayValue)).ToArgb();      //Color转byte
            }

            bmpobj.UnlockBits(bmpData);
        }

        /// <summary>
        /// 得到有效图形并调整为可平均分割的大小
        /// </summary>
        /// <param name="dgGrayValue">灰度背景分界值</param>
        /// <param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public void GetPicValidByValue(int dgGrayValue, int CharsCount)
        {
            int posx1 = bmpobj.Width; int posy1 = bmpobj.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < bmpobj.Height; i++)      //找有效区
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    int pixelValue = bmpobj.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            // 确保能整除
            int Span = CharsCount - (posx2 - posx1 + 1) % CharsCount;   //可整除的差额数
            if (Span < CharsCount)
            {
                int leftSpan = Span / 2;    //分配到左边的空列 ，如span为单数,则右边比左边大1
                if (posx1 > leftSpan)
                    posx1 = posx1 - leftSpan;
                if (posx2 + Span - leftSpan < bmpobj.Width)
                    posx2 = posx2 + Span - leftSpan;
            }
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            bmpobj = bmpobj.Clone(cloneRect, bmpobj.PixelFormat);
        }

        /// <summary>
        /// 得到有效图形,图形为类变量
        /// </summary>
        /// <param name="dgGrayValue">灰度背景分界值</param>
        /// <param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public void GetPicValidByValue(int dgGrayValue)
        {
            int posx1 = bmpobj.Width; int posy1 = bmpobj.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < bmpobj.Height; i++)      //找有效区
            {
                for (int j = 0; j < bmpobj.Width; j++)
                {
                    int pixelValue = bmpobj.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            bmpobj = bmpobj.Clone(cloneRect, bmpobj.PixelFormat);
        }

        /// <summary>
        /// 得到有效图形,图形由外面传入
        /// </summary>
        /// <param name="dgGrayValue">灰度背景分界值</param>
        /// <param name="CharsCount">有效字符数</param>
        /// <returns></returns>
        public Bitmap GetPicValidByValue(Bitmap singlepic, int dgGrayValue)
        {
            int posx1 = singlepic.Width; int posy1 = singlepic.Height;
            int posx2 = 0; int posy2 = 0;
            for (int i = 0; i < singlepic.Height; i++)      //找有效区
            {
                for (int j = 0; j < singlepic.Width; j++)
                {
                    int pixelValue = singlepic.GetPixel(j, i).R;
                    if (pixelValue < dgGrayValue)     //根据灰度值
                    {
                        if (posx1 > j) posx1 = j;
                        if (posy1 > i) posy1 = i;

                        if (posx2 < j) posx2 = j;
                        if (posy2 < i) posy2 = i;
                    };
                };
            };
            //复制新图
            Rectangle cloneRect = new Rectangle(posx1, posy1, posx2 - posx1 + 1, posy2 - posy1 + 1);
            return singlepic.Clone(cloneRect, singlepic.PixelFormat);
        }

        /// <summary>
        /// 平均分割图片
        /// </summary>
        /// <param name="RowNum">水平上分割数</param>
        /// <param name="ColNum">垂直上分割数</param>
        /// <returns>分割好的图片数组</returns>
        public Bitmap[] GetSplitPics(int RowNum, int ColNum)
        {
            if (RowNum == 0 || ColNum == 0)
                return null;
            int singW = bmpobj.Width / RowNum;
            int singH = bmpobj.Height / ColNum;
            Bitmap[] PicArray = new Bitmap[RowNum * ColNum];

            Rectangle cloneRect;
            for (int i = 0; i < ColNum; i++)      //找有效区
            {
                for (int j = 0; j < RowNum; j++)
                {
                    cloneRect = new Rectangle(j * singW, i * singH, singW, singH);
                    PicArray[i * RowNum + j] = bmpobj.Clone(cloneRect, bmpobj.PixelFormat);//复制小块图
                }
            }
            return PicArray;
        }

        /// <summary>
        /// 返回灰度图片的点阵描述字串，1表示灰点，0表示背景
        /// </summary>
        /// <param name="singlepic">灰度图</param>
        /// <param name="dgGrayValue">背前景灰色界限</param>
        /// <returns></returns>
        public string GetSingleBmpCode(Bitmap singlepic, int dgGrayValue)
        {
            Color piexl;
            string code = "";
            for (int posy = 0; posy < singlepic.Height; posy++)
                for (int posx = 0; posx < singlepic.Width; posx++)
                {
                    piexl = singlepic.GetPixel(posx, posy);
                    if (piexl.R < dgGrayValue)    // Color.Black )
                        code = code + "1";
                    else
                        code = code + "0";
                }
            return code;
        }
        /// <summary>
        /// 识别验证码
        /// </summary>
        public string GetVerifyCode()
        {
            GrayByPixels(); //灰度处理
            GetPicValidByValue(128, 4); //得到有效空间
            Bitmap[] pics = GetSplitPics(4, 1);//分割
            string codeResult = "";
            LevenshteinDistance levenshteinDistance = new LevenshteinDistance();

            List<string> traning0 = new List<string> {
                    "11110000000100001000000100001000000100001000000000001000000000010000000000100000000001000000000010000000000100001000000111111000000000000000000",
                    "11000000000100100000001000010000001000010000001000010000001000010000001000010000001000010000001000010000000100100000000011000000000000000",
                    "11110000000010000100000011000011000001100000100000100000010000010000001000001000000100000110000010000011000011000000100001000000001111000000",
                    "1100000000010010000000100001000000100001000000100001000000100001000000100001000000100001000000100001000000010010000000001100",
                    "111100000001000010000011000011000011000001000010000001000010000001000010000001000011000001000011000011000001000010000000111100",
                    "11000000000100100000001000010000001000010000001000010000001000010000001000010000001000010000001000010000000100100000000011000000000000000000",
                    "1100000000001001000000001000010000000100001000000010000100000001000010000000100001000000010000100000001000010000000010010000000000110000000000000000000000000000000000",
                    "111100000000100001000000110000110000011000001000001000000100000100000010000010000001000001100000100000110000110000001000010000000011110000",
                    "1100000000010010000000100001000000100001000000100001000000100001000000100001000000100001000000100001000000010010000000001100000000000000",
                    "11000000000100100000001000010000001000010000001000010000001000010000001000010000001000010000001000010000000100100000000011000000",
                };
            List<string> traning1 = new List<string> {
                   "100000000011100000000000100000000000100000000000100000000000100000000000100000000000100000000000100000000000100000000011111000000000000",
                   "100000000001110000000000001000000000000100000000000010000000000001000000000000100000000000010000000000001000000000000100000000001111100000000",
                   "100000000011100000000000100000000000100000000000100000000000100000000000100000000000100000000000100000000000100000000011111000000",
                   "1000000000111000000000001000000000001000000000001000000000001000000000001000000000001000000000001000000000001000000000111110000",
                   "1000000000011100000000000010000000000001000000000000100000000000010000000000001000000000000100000000000010000000000001000000000011111000000000000000000",
                   "1000000000111000000000001000000000001000000000001000000000001000000000001000000000001000000000001000000000001000000000111110000000",
                   "1000000000011100000000000010000000000001000000000000100000000000010000000000001000000000000100000000000010000000000001000000000011111000",
                   "1000000000111000000000001000000000001000000000001000000000001000000000001000000000001000000000001000000000001000000000111110000000",
                 };
            List<string> traning2 = new List<string> {
                    "11110000000010001100000010000011000001000001100000000000110000000000010000000000010000000000010000000000010000000000100000100000111111110000",
                    "11110000000010001100000010000011000001000001100000000000110000000000010000000000010000000000010000000000010000000000100000100000111111110",
                    "1111000000001000010000000100001000000010000100000000000010000000000010000000000010000000000010000000000010000000000010000100000001111110000000000000000000",
                    "11110000000100001000000100001000000100001000000000001000000000010000000000100000000001000000000010000000000100001000000111111000000000000000000",
                    "111100000001000010000001000010000001000010000000000010000000000100000000001000000000010000000000100000000001000010000001111110",
                    "111100000000100011000000100000110000010000011000000000001100000000000100000000000100000000000100000000000100000000001000001000001111111100000000000000",
                    "11110000000100001000000100001000000100001000000000001000000000010000000000100000000001000000000010000000000100001000000111111000000",
                    "11110000000010000100000001000010000000100001000000000000100000000000100000000000100000000000100000000000100000000000100001000000011111100000000000000000",
                    "1111000000010001100000100000110000100000110000000000110000000000100000000001000000000010000000000100000000010000010000111111110000",
                };
            List<string> traning3 = new List<string> {
                    "11110000000100001000000100001000000000001000000000010000000001100000000000010000000000001000000100001000000100001000000011110000000",
                    "11110000000100001000000100001000000000001000000000010000000001100000000000010000000000001000000100001000000100001000000011110",
                    "11110000000010000100000001000010000000000001000000000001000000000011000000000000010000000000000100000001000010000000100001000000001111000000000000000000",
                    "111100000001000010000001000011000000000010000000000100000000011110000000000011000000000001000011000001000001000011000000111100",
                };
            List<string> traning4 = new List<string> {
                    "100000000000110000000000011000000000010100000000010010000000001001000000001000100000000111111100000000001000000000000100000000001111100000000000000000",
                    "10000000000110000000000110000000001010000000010010000000100010000000100010000001111111100000000010000000000010000000000111000",
                    "100000000000110000000000011000000000010100000000010010000000001001000000001000100000000111111100000000001000000000000100000000001111100",
                    "1000000000011000000000011000000000101000000001001000000010001000000010001000000111111110000000001000000000001000000000011100000",
                    "10000000000011000000000001100000000001010000000001001000000001000100000000100010000000111111110000000000100000000000010000000000011100000",
                    "100000000000110000000000011000000000010100000000010010000000001001000000001000100000000111111100000000001000000000000100000000001111100000000000000000",
                    "1000000000001100000000000110000000000101000000000100100000000010010000000010001000000001111111000000000010000000000001000000000011111000000000000000",
                    "1000000000001100000000000110000000000101000000000100100000000010010000000010001000000001111111000000000010000000000001000000000011111000000000000000",
                };
            List<string> traning5 = new List<string> {
                    "1111110000001000000000001000000000001000000000001111000000001000100000000000010000000000010000001000010000001000100000000111000000",
                    "111111000000100000000000100000000000100000000000111100000000100010000000000001000000000001000000100001000000100010000000011100000000",
                    "111111000000100000000000100000000000100000000000111100000000100010000000000001000000000001000000100001000000100010000000011100000000000000000000",
                    "1111110000000100000000000010000000000001000000000000111100000000010001000000000000010000000000001000000010000100000001000100000000011100000000000000000000000000000000",
                    "1111110000000100000000000010000000000001000000000000111100000000010001000000000000010000000000001000000010000100000001000100000000011100000000",
                    "1111111000000100000000000010000000000001111100000000000001100000000000010000000000001000000100000100000010000110000000110110000",
                    "1111110000001000000000001000000000001000000000001111000000001000100000000000010000000000010000001000010000001000100000000111000000000000000000",
                    "111111000000100000000000100000000000100000000000111100000000100010000000000001000000000001000000100001000000100010000000011100000000",
                    "11111100000010000000000010000000000010000000000011110000000010001000000000000100000000000100000010000100000010001000000001110000",
                    "111111000000100000000000100000000000100000000000111100000000100010000000000001000000000001000000100001000000100010000000011100",
                };
            List<string> traning6 = new List<string> {
                    "1100000000010010000000100000000000100000000000101110000000110001000000100001000000100001000000100001000000010001000000001110000000000000",
                    "111000000001100000000001100000000000100000000000110001000000011000011000001100000100000110000010000011000001000000100001100000011111100000000001000000",
                    "110000000001001000000010000000000010000000000010111000000011000100000010000100000010000100000010000100000001000100000000111000",
                    "110000000000100100000000100000000000010000000000001011100000000110001000000010000100000001000010000000100001000000001000100000000011100000",
                };
            List<string> traning7 = new List<string> {
                    "11111100000010000100000000001000000000001000000000010000000000010000000000100000000000100000000000100000000000100000000000100000000000000000000",
                    "111111100000100000000000000000010000000000010000000000001000000000001000000000001100000000000110000000000010000000000001000000000001100000",
                    "111111000000100001000000000010000000000010000000000100000000000100000000001000000000001000000000001000000000001000000000001000000",
                    "1111110000001000010000000000100000000000100000000001000000000001000000000010000000000010000000000010000000000010000000000010000000",
                    "111111000000010000100000000000100000000000010000000000010000000000001000000000001000000000000100000000000010000000000001000000000000100000000",
                    "111111100000100000000000000000010000000000010000000000001000000000001000000000001100000000000110000000000010000000000001000000000001100000000",
               };
            List<string> traning8 = new List<string> {
                    "11110000000100001000000100001000000100001000000000001000000000010000000000100000000001000000000010000000000100001000000111111000000000000000000",
                    "11110000000100011000001000001100001000001100000000001100000000001000000000010000000000100000000001000000000100000100001111111100",
                    "111100000000100001000000010000110000001000010000000110010000000000011000000001000011000001000000100000100000010000011000011000000011110000",
                    "1111000000010000100000010000100000010000100000001001000000000110000000001001000000010000100000010000100000010000100000001111000000000000000",
                    "1111000000010000100000010000100000010000100000001001000000000110000000001001000000010000100000010000100000010000100000001111000",
                    "11110000000100001000000100001000000100001000000010010000000001100000000010010000000100001000000100001000000100001000000011110000000000000000000",
                    "111100000001000010000001000010000001000010000000100100000000011000000000100100000001000010000001000010000001000010000000111100000",
                };
            List<string> traning9 = new List<string> {
                    "11100000000100010000000100001000000100001000000100001000000100011000000011101000000000001000000000001000000010010000000001100000000000000000",
                    "1110000000010001000000010000100000010000100000010000100000010001100000001110100000000000100000000000100000001001000000000110000",
                    "1111000000011000010000001100001100000100000110000010000011000001100001100000011111110000000000011000000000001000000000001000000001111000000",
                    "11110000000110000100000011000011000001000001100000100000110000011000011000000111111100000000000110000000000010000000000010000000011110000",
                    "111000000001000100000001000010000001000010000001000010000001000110000000111010000000000010000000000010000000100100000000011000000000000000000",
                    "11100000000100010000000100001000000100001000000100001000000100011000000011101000000000001000000000001000000010010000000001100",
                    "111100000011000010000011000011000010000011000010000011000011000011000001111111000000000011000000000010000000000100000001111000",
                };
            List<List<string>> traning = new List<List<string>> { traning0, traning1, traning2, traning3, traning4, traning5, traning6, traning7, traning8, traning9 };

            for (int i = 0; i < pics.Length; i++)
            {
                string code = GetSingleBmpCode(pics[i], 128);

                Console.WriteLine(code);
                List<List<double>> match = new List<List<double>>() { new List<double>(), new List<double>(), new List<double>(), new List<double>(), new List<double>(), new List<double>(), new List<double>(), new List<double>(), new List<double>(), new List<double>() };
                double MaxMatch = 0;
                double MaxMatchCode = 0;
                for (int traningIndex = 0; traningIndex < traning.Count; traningIndex++)
                {
                    for (int traningIndexj = 0; traningIndexj < traning[traningIndex].Count; traningIndexj++)
                    {
                        levenshteinDistance.Compute(RemoveZeroBeforeOne(traning[traningIndex][traningIndexj]), RemoveZeroBeforeOne(code));
                        match[traningIndex].Add(Convert.ToDouble(levenshteinDistance.ComputeResult.Rate));

                    }
                }
                for (int matchIndex = 0; matchIndex < match.Count; matchIndex++)
                {
                    double matchjSum = 0;
                    for (int matchIndexj = 0; matchIndexj < match[matchIndex].Count; matchIndexj++)
                    {
                        //matchjSum += match[matchIndex][matchIndexj];
                        if (MaxMatch < match[matchIndex][matchIndexj])
                        {
                            MaxMatch = match[matchIndex][matchIndexj];
                            MaxMatchCode = matchIndex;
                        }
                    }
                }
                codeResult += MaxMatchCode;
            }
            Console.WriteLine(codeResult);
            return codeResult;
        }

        /// <summary>
        /// 去除字符串前面的所有0
        /// </summary>
        /// <param name="SourceStr"></param>
        /// <returns></returns>
        public string RemoveZeroBeforeOne(string SourceStr)
        {
            int len = SourceStr.Length;// 取得字符串的长度
            int index = 0;// 预定义第一个非零字符串的位置

            char[] strs = SourceStr.ToCharArray();// 将字符串转化成字符数组
            for (int i = 0; i < len; i++)
            {
                if ('0' != strs[i])
                {
                    index = i;// 找到非零字符串并跳出
                    break;
                }
            }
            string strLast = SourceStr.Substring(index, len- index);// 截取字符串
            return strLast;
        }
    }
    
}
